import { cloneElement, Suspense, useCallback, useEffect, useRef, useState } from "react";
import { useLocation,useNavigate, useOutlet } from "react-router-dom";
import { Layout } from "antd";
import { updateCollapse } from "@/redux/feature/menuSlice";
import { connect } from "react-redux";
import LayoutMenu from "./components/Menu";
import LayoutHeader from "./components/Header";
import LayoutTabs from "./components/Tabs";
import LayoutFooter from "./components/Footer";
import "./index.less";
import { useMemo } from "react";
import KeepAlive, { useKeepAliveRef } from "keepalive-for-react";

const LayoutIndex = (props: any) => {
	const { Sider, Content } = Layout;
	const { isCollapse, updateCollapse } = props;
	
	const location = useLocation();
    const aliveRef = useKeepAliveRef();
    const outlet = useOutlet();

    // determine which route component to is active
    const currentCacheKey = useMemo(() => {
        return location.pathname + location.search;
    }, [location.pathname, location.search]);
	console.log('currentCacheKey','[' + currentCacheKey + ']')
	// 监听窗口大小变化
	const listeningWindow = () => {
		window.onresize = () => {
			return (() => {
				let screenWidth = document.body.clientWidth;
				if (!isCollapse && screenWidth < 1200) updateCollapse(true);
				if (!isCollapse && screenWidth > 1200) updateCollapse(false);
			})();
		};
	};

	useEffect(() => {
		listeningWindow();
	}, []);

	return (
		// 这里不用 Layout 组件原因是切换页面时样式会先错乱然后在正常显示，造成页面闪屏效果
		<section className="container">
			<Sider trigger={null} collapsed={props.isCollapse} width={220} theme="dark">
				<LayoutMenu></LayoutMenu>
			</Sider>
			<Layout>
				<LayoutHeader></LayoutHeader>
				<LayoutTabs aliveRef={aliveRef}></LayoutTabs>
				<Content>
				<KeepAlive transition aliveRef={aliveRef} activeCacheKey={currentCacheKey} max={18}>
                    {outlet}
                </KeepAlive>
				</Content>
				<LayoutFooter></LayoutFooter>
			</Layout>
		</section>
	);
};

const mapStateToProps = (state: any) => state.menu;
const mapDispatchToProps = { updateCollapse };
export default connect(mapStateToProps, mapDispatchToProps)(LayoutIndex);
